package com.asana.resteasy.api.util;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.*;

public class GSonParser {

	public static JsonSerializer<Date> serializeDate = new JsonSerializer() {
		
		@Override
		public JsonElement serialize(Object arg0, Type arg1,JsonSerializationContext arg2) {
			Date src = (Date) arg0;
			return src == null ? null : new JsonPrimitive(src.getTime());
		}		
	
	}; 
	
	public static JsonDeserializer<Date> deserializeDate = new JsonDeserializer() {
		
		@Override
		public Object deserialize(JsonElement json, Type arg1,	JsonDeserializationContext arg2) throws JsonParseException {
			
			String date = json.getAsString();
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			Date ret = null;
			try {
				if (ret == null)
					ret = sdf1.parse(date);
			} catch (ParseException e) {
			}

			try {
				if (ret == null)
					ret = sdf2.parse(date);
			} catch (ParseException e) {
			}

			return ret;
		}		
	
	}; 
		
}
